package com.example.springboot.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;

import java.util.Date;

@Component
public class TokenUtils {
    public static UserMapper staticuserMapper;
    @Resource
    UserMapper userMapper;
    @PostConstruct
    public void setUserMapper(){
        staticuserMapper=userMapper;
    }
    /**
     * 生成token
     */
    public static String createToken(String userId,String sign){
        return JWT.create().withAudience(userId)//将user id保存到token 里面
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))// 设置过期时间
                .sign(Algorithm.HMAC256(sign));// 以password作为token的密钥
    }
    public static User getCurrrentUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if(StrUtil.isNotBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return staticuserMapper.selectById(Integer.valueOf(userId));
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }
}
